package com.testitems.controller.user;

import com.testitems.enums.RoleEnum;
import com.testitems.common.web.page.PageInfo;
import com.testitems.common.web.result.Result;
import com.testitems.config.security.UserInfo;
import com.testitems.controller.user.dto.UserCreateRequest;
import com.testitems.controller.user.dto.UserSearchRequest;
import com.testitems.controller.user.dto.UserUpdateRequest;
import com.testitems.repo.entity.User;
import com.testitems.service.user.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author GFH
 * @since 2021-11-20
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "用户列表查询", notes = "目前没有条件")
    @PostMapping("/search")
    public Result userSearch(@RequestBody UserSearchRequest request) {
        PageInfo<User> search = userService.search(request);
        return Result.ok(search);
    }

    @PostMapping("/addUser")
    @ApiOperation(value = "新建用户")
    public Result register(@Validated @RequestBody UserCreateRequest params,
                           @ApiIgnore @AuthenticationPrincipal UserInfo userInfo) {

        if (params.getRoleLevel() != RoleEnum.ADMIN.getId() && params.getRoleLevel() != RoleEnum.EMPLOYEE.getId()) {
            return Result.fail("请输入正确的roleLevel");
        }
        if (!params.getPassword().equals(params.getRePassword())) {
            return Result.fail("两次密码不一致");
        }
        User user = userService.getByUserName(params.getUsername());
        if (user != null) {
            return Result.fail("当前账户已经存在");
        }
        userService.createdUser(params, userInfo);
        return Result.ok();
    }

    @ApiOperation(value = "编辑")
    @PutMapping("/{id}")
    public Result update(@PathVariable Integer id, @Validated @RequestBody UserUpdateRequest request,
                         @ApiIgnore @AuthenticationPrincipal UserInfo userInfo){
        userService.updateByUserId(id,request,userInfo);
        return Result.ok();
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    public Result deletedById(@PathVariable Integer id, @ApiIgnore @AuthenticationPrincipal UserInfo userInfo) {
        userService.logicDelete(id, userInfo);
        return Result.ok();
    }
}
